﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.Text;
using System.Data;
using Microsoft.Reporting.WebForms;

namespace Apps.Common
{
    /// <summary>
    /// PrintHelper 的摘要描述
    /// </summary>
    public class PrintHelper
    {
        private int m_currentPageIndex;
        private IList<Stream> m_streams;
        private bool isLandSapces = false;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="reportPath">rdlc路径</param>
        /// <param name="printerName">打印机名称</param>
        /// <param name="dt1">数据表集数据</param>
        /// <param name="dt1SourceName">数据对应rdlc中的数据集名称</param>
        /// <param name="paramesList">报表参数集合</param>
        /// <param name="isHindeLogo">是否隐藏</param>
        /// <param name="msg">输出信息</param>
        /// <param name="reportWidth">报表长度（单位：mm）</param>
        public void Run(string reportPath, string printerName, object dt1, string dt1SourceName, List<Microsoft.Reporting.WebForms.ReportParameter> paramesList, bool isHindeLogo, out string msg, int reportWidth = 430)
        {
            LocalReport report = new LocalReport();

            report.ReportPath = reportPath;//加上报表的路径
            report.DataSources.Add(new ReportDataSource(dt1SourceName, dt1));
            report.EnableExternalImages = true;
            report.SetParameters(paramesList);
            isLandSapces = report.GetDefaultPageSettings().IsLandscape;
            Export(report, reportWidth);
            m_currentPageIndex = 0;
            Print(string.IsNullOrEmpty(printerName) ? new PrinterSettings().PrinterName : printerName, out msg);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="report"></param>
        /// <param name="reportWidth">报表长度（单位：mm）</param>
        private void Export(LocalReport report, int reportWidth = 430)
        {
            string deviceInfo =
              "<DeviceInfo>" +
              "  <OutputFormat>EMF</OutputFormat>" +
              "  <PageWidth>" + reportWidth + "mm</PageWidth>" +
              "  <PageHeight>297mm</PageHeight>" +
              "  <MarginTop>5mm</MarginTop>" +
              "  <MarginLeft>10mm</MarginLeft>" +
              "  <MarginRight>10mm</MarginRight>" +
              "  <MarginBottom>5mm</MarginBottom>" +
              "</DeviceInfo>";//这里是设置打印的格式 边距什么的
            Warning[] warnings;
            m_streams = new List<Stream>();
            try
            {
                report.Render("Image", deviceInfo, new CreateStreamCallback(CreateStream), out warnings);//一般情况这里会出错的  使用catch得到错误原因  一般都是简单错误

            }
            catch (Exception ex)
            {
                Exception innerEx = ex.InnerException;//取内异常。因为内异常的信息才有用，才能排除问题。
                while (innerEx != null)
                {
                    string errmessage = innerEx.Message;
                    innerEx = innerEx.InnerException;
                }
            }
            foreach (Stream stream in m_streams)
            {
                stream.Position = 0;
            }
        }
        string ssss = "--";
        private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
        {
            Stream stream = null;
            try
            {
                 stream = new FileStream(Path.GetTempPath() + name + "." + fileNameExtension, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                 m_streams.Add(stream);
            }
            catch (Exception ex)
            {
                ssss = ex.Message;
            }
            return stream;
        }


        private void Print(string printerName, out string msg)
        {
            
            msg = "";
            //string printerName = this.TextBox1.Text.Trim();// "傳送至 OneNote 2007";
            if (m_streams == null || m_streams.Count == 0)
            {
                msg = "没有要打印的数据，请重试";
                return;
            }

            PrintDocument printDoc = new PrintDocument();
            if (printerName.Length > 0)
            {
                printDoc.PrinterSettings.PrinterName = printerName;
                printDoc.DefaultPageSettings.Landscape = isLandSapces;
            }


            foreach (PaperSize ps in printDoc.PrinterSettings.PaperSizes)
            {
                if (ps.PaperName == "A4")
                {
                    printDoc.DefaultPageSettings.PaperSize = ps;
                    // printDoc.PrinterSettings.IsDefaultPrinter;//知道是否是预设定的打印机
                }
            }
            if (!printDoc.PrinterSettings.IsValid)
            {
                msg = String.Format("找不到打印机: " + printDoc.PrinterSettings.PrinterName);
                System.Diagnostics.Debug.WriteLine(msg);
                return;
            }
            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            printDoc.Print();
        }

        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]);         //设置高质量插值法
            ev.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            ev.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            ev.Graphics.DrawImage(pageImage, new System.Drawing.Rectangle(0, 0, ev.PageBounds.Width, ev.PageBounds.Height), new System.Drawing.Rectangle(0, 0, pageImage.Width, pageImage.Height), System.Drawing.GraphicsUnit.Pixel);
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);

        }
    }
}